#include "TreeWidgetShell.h"

TreeWidgetShell::TreeWidgetShell(QObject *parent)
    : QObject (parent){
    _treeWidget = nullptr;
}

void TreeWidgetShell::shell(QTreeWidget *treeWidget){
    if(_treeWidget){
        return;
    }
    _treeWidget = treeWidget;
    connect(_treeWidget,&QTreeWidget::itemClicked,this,&TreeWidgetShell::treeWidget_onItemClicked);
}
void TreeWidgetShell::configColumn( const QStringList &key){
    if(!_treeWidget){
        return;
    }
    _treeWidget->setColumnCount(key.count());
    _columnKey = key;
}

void TreeWidgetShell::setData(const QList<QVariant> &data){
    if(!_treeWidget){
        return;
    }
    _treeWidget->clear();
    for (int index=0; index<data.count(); index++) {
        QVariantMap sectionData = data[index].toMap();

        // Header
        QString header = sectionData["_Header_"].toString();
        QTreeWidgetItem *headerItem = new QTreeWidgetItem(_treeWidget);
        headerItem->setText(0,header);
        _treeWidget->addTopLevelItem(headerItem);

        // Row
        QList<QVariant> rowDatas = sectionData["_Row_"].toList();
        foreach(auto rowData, rowDatas){
            if(rowData.type() == QVariant::String){
                QTreeWidgetItem *rowItem = new QTreeWidgetItem;
                headerItem->addChild(rowItem);
                rowItem->setText(0,rowData.toString());
            }
            else if(rowData.type() == QVariant::Map){
                QVariantMap map = rowData.toMap();
                QTreeWidgetItem *rowItem = new QTreeWidgetItem;
                headerItem->addChild(rowItem);
                for (int col=0; col<_columnKey.count(); col++) {
                    rowItem->setText(col,map[_columnKey[col]].toString());
                }
            }
            else{

            }
        }
    }
}
QVariantMap TreeWidgetShell::getSectionData(int section){
    if(_data.isEmpty() || section>=_data.count()){
        return QVariantMap();
    }
    return _data[section].toMap();
}
QList<QVariant> TreeWidgetShell::getRowData(int section){
    if(_data.isEmpty() || section>=_data.count()){
        return QList<QVariant>();
    }

    QVariantMap sectionData = getSectionData(section);
    return sectionData.contains("_Row_") ? sectionData["_Row_"].toList() : QList<QVariant>();
}
QVariant TreeWidgetShell::getRowData(int section, int row){
    QList<QVariant> rowData = getRowData(section);
    if(rowData.isEmpty() || row >= rowData.count()){
        return QVariant();
    }
    return rowData[row];
}

void TreeWidgetShell::treeWidget_onItemClicked(QTreeWidgetItem *item, int column){
    if()
}
